package elements;

import java.util.ArrayList;

/**
 * Un nod al arborelui.
 */

public class Node<T> {
 
    public T data;
    public ArrayList<Node<T>> children;
 
    public Node() {
        super();
    }
 
    public Node(T data) {
        this();
        setData(data);
    }
     
    /**
     * Returneaza lista de copii ai nodului curent.
     */
    public ArrayList<Node<T>> getChildren() {
        if (this.children == null) {
            return new ArrayList<Node<T>>();
        }
        return this.children;
    }
 
    public Node<T> getChild(T data)
    {
		
    	for(Node<T> e : getChildren())
    		if(e.getData().equals(data))
    			return e;
    	return null;
    	
    }
    /**
     * Seteaza copii nodului curent.
     */
    public void setChildren(ArrayList<Node<T>> children) {
        this.children = children;
    }
 
    /**
     * Returneaza numarul de copii ai nodului curent.
     */
    public int getNumberOfChildren() {
        if (children == null) {
            return 0;
        }
        return children.size();
    }
     
    /**
     * Adauga un nou copil in lista de noduri fii; daca se doreste inserarea
     * primului copil, se va initializa lista in prealabil. 
     */
    public void addChild(Node<T> child) {
        if (children == null) {
            children = new ArrayList<Node<T>>();
        }
        children.add(child);
    }
     
    /**
     * Insereaza un nou copil pe o pozitie data.
     */
    public void insertChildAt(int index, Node<T> child) throws IndexOutOfBoundsException {
        if (index == getNumberOfChildren()) {
            // this is really an append
            addChild(child);
            return;
        } else {
            children.get(index); //just to throw the exception, and stop here
            children.add(index, child);
        }
    }
     
    /**
     * Sterge un copil de pe o pozitie data.
     */
    public void removeChildAt(int index) throws IndexOutOfBoundsException {
        children.remove(index);
    }
 
    public T getData() {
        return this.data;
    }
 
    public void setData(T data) {
        this.data = data;
    }
     
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{").append(getData().toString()).append(",[");
        int i = 0;
        for (Node<T> e : getChildren()) {
            if (i > 0) {
                sb.append(",");
            }
            sb.append(e.getData().toString());
            i++;
        }
        sb.append("]").append("}").append("\n");
        return sb.toString();
    }
}
